from .spider_dangdang import spider as dang_dang
from .spider_jd import spider as jd
import openpyxl


def main(book_name):
    """ 图书比价工具整合 """
    jd_list = []
    dd_list = []
    # 当当网的数据
    print('当当网数据爬取完成')
    dang_dang(book_name, dd_list)

    # 京东网数据
    print('京东网数据爬取完成')
    jd(book_name, jd_list)

    print('----------------开始排序-----------')

    # 排序书的数据
    jd_list = sorted(jd_list, key=lambda item: float(item["price"]), reverse=False)
    dd_list = sorted(dd_list, key=lambda item: float(item["price"]), reverse=False)
    save_excel('京东', book_name, jd_list)
    save_excel('当当', book_name, dd_list)


def save_excel(shop_name, book_name, book_list):
    # 创建excel
    xls = openpyxl.Workbook()
    # 激活sheet
    sheet = xls.active
    # 要保存的列头
    title = ['书名', '链接', '价格']
    # 添加列头
    sheet.append(title)
    for item in book_list:
        sheet.append([item['title'], item['link'], item['price']])
    # 表名
    file_name = shop_name + book_name
    # 保存
    dir_name = './data/'
    xls.save(dir_name + file_name + '.xlsx')
    print("----------------保存成功-----------")


if __name__ == '__main__':
    book_name = input('请输入书名:')
    main(book_name)
